import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'
import { throwError } from 'rxjs'
import { catchError, retry } from 'rxjs/operators'
import { Router, ActivatedRoute } from '@angular/router'
import { environment } from './../../../environments/environment'
import { Toast } from 'ng-zorro-antd-mobile'

@Injectable({
    providedIn: 'root'
})
export class HttpClientService {
    public baseUrl = environment.baseUrl
    public httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    }

    constructor(
        private router: Router,
        private activeRoute: ActivatedRoute,
        private http: HttpClient,
        private toast: Toast
    ) { }

    /**
     * post请求
     * @param reqdata 请求参数
     * @param url 请求地址
     * @param callBack 成功回调
     * @param errorBack 异常回调
     */
    post(reqdata, url, callBack, errorBack?) {
        this._post(reqdata, url).subscribe(
            res => {
                if (callBack) {
                    callBack(res)
                }
            },
            error => {
                if (errorBack) {
                    errorBack(error)
                } else {
                    this._error(error)
                }
                // 未登录状态
                if (error.status === 401) {
                    let whitelist = [
                        '/workspace/home/index',
                        '/workspace/discover/index',
                        '/workspace/follow/index',
                        '/workspace/mine/index'
                    ]
                    // 且不在白名单内，说明需要跳转到登录页面
                    if (whitelist.indexOf(this.router.url) === -1) {
                        this.router.navigate(['/register'])
                    }
                }
            }
        )
    }

    /**
     * get 请求
     * @param url 请求地址
     * @param callBack 成功回调
     * @param errorBack 异常回调
     */
    get(url, callBack, errorBack?) {
        this._get(url).subscribe(
            res => {
                if (callBack) {
                    callBack(res)
                }
            },
            error => {
                if (errorBack) {
                    errorBack(error)
                } else {
                    this._error(error)
                }
                // 未登录状态
                if (error.status === 401) {
                    let whitelist = [
                        '/workspace/home/index',
                        '/workspace/discover/index',
                        '/workspace/follow/index',
                        '/workspace/mine/index'
                    ]
                    // 且不在白名单内，说明需要跳转到登录页面
                    if (whitelist.indexOf(this.router.url) === -1) {
                        this.router.navigate(['/register'])
                    }
                }
            }
        )
    }

    /**
     * post请求 （自定义头可用该方法）
     * @param reqdata 请求参数
     * @param url 请求地址
     * @param headers 请求头
     */
    _post(reqdata, url, headers?) {
        // let _url = this.baseUrl + url
        let _url = url
        if (url.indexOf('http') === -1) {
            _url = this.baseUrl + url
        }

        //自定义请求头
        if (headers) {
            this._setHeader(headers)
        }

        return this.http.post(_url, reqdata, this.httpOptions).pipe(catchError(this.handleError))
    }

    //图片上传
    imgUpLoad(formData,url,callback,errorback?){

        let _url = this.baseUrl + url
        let xhr = new XMLHttpRequest();
        //完成
        xhr.addEventListener("load", (event: any) => { 
            callback(event.currentTarget.response)
        }, false);
        xhr.addEventListener("error", (e)=>{
            if(errorback){
                errorback(e)
            }
        })
        xhr.open("POST", _url);
        xhr.send(formData);
    }
    /**
     * get请求
     * @param url 请求地址
     */
    _get(url,headers?) {
        // let _url = this.baseUrl + url
        let _hd =  {
            headers: new HttpHeaders({
                'data-Type': 'jsonp'
            })
        }
        
        let _url = url
        if (url.indexOf('http') === -1) {
            _url = this.baseUrl + url
        }

        return this.http.get(_url,_hd).pipe(
            //网络异常 再次发送请求（会连发三次）
            // retry(3),
            catchError(this.handleError)
        )
    }

    /**
     * 默认异常处理
     * @param err 异常对象体
     */
    _error(err) { }

    /**
     * 自定义请求头
     * @param headers 请求头
     */
    _setHeader(headers) {
        for (const key in headers) {
            if (headers.hasOwnProperty(key)) {
                const element = headers[key]
                this.httpOptions.headers = this.httpOptions.headers.set(key, element)
            }
        }
    }

    // 异常拦截
    private handleError(error: HttpErrorResponse) {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        console.error(error)
        // return an observable with a user-facing error message
        return throwError(error)
    }
}
